package com.deshan.websys.api.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.deshan.websys.api.utils.CommonResult;
import com.deshan.websys.code.model.Customers;
import com.deshan.websys.code.model.PmsComment;
import com.deshan.websys.code.model.PmsIm;
import com.deshan.websys.code.model.PmsKeyWord;
import com.deshan.websys.code.model.PmsNotice;
import com.deshan.websys.code.model.PmsPageSetItem;
import com.deshan.websys.code.model.SmsHomeAdvertise;
import com.deshan.websys.code.model.UmsRose;
import com.deshan.websys.code.model.UmsUser;
import com.deshan.websys.code.model.vo.CorporationVO;
import com.deshan.websys.code.model.vo.CustomersVO;
import com.deshan.websys.code.model.vo.LoginVO;
import com.deshan.websys.code.model.vo.PmsCommentVO;
import com.deshan.websys.code.model.vo.VisitLogVO;
import com.deshan.websys.code.service.ClickService;
import com.deshan.websys.code.service.CmsMinutesService;
import com.deshan.websys.code.service.CmsPageSetService;
import com.deshan.websys.code.service.CustomersService;
import com.deshan.websys.code.service.PmsCommentService;
import com.deshan.websys.code.service.PmsCrawlerService;
import com.deshan.websys.code.service.PmsImService;
import com.deshan.websys.code.service.PmsKeyWordService;
import com.deshan.websys.code.service.PmsNoticeService;
import com.deshan.websys.code.service.PmsStatisticsService;
import com.deshan.websys.code.service.PmsVisitLogService;
import com.deshan.websys.code.service.SmsHomeAdvertiseService;
import com.deshan.websys.code.service.UmsRoseService;
import com.deshan.websys.code.service.UmsUserService;
import com.deshan.websys.code.service.VisitorClick;
import com.deshan.websys.code.utils.RestResult;
import com.deshan.websys.code.utils.StringUtils;
import com.deshan.websys.code.utils.UuidUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

/**
 * 首页内容管理Controller Created by macro on 2019/1/28.
 */
@Controller
@Api(tags = "法人主页相关接口")
//@Tag(name = "HomeController", description = "首页内容管理")
@RequestMapping("/api")
@Slf4j
public class HomeController {

	@Autowired
	SmsHomeAdvertiseService smsHomeAdvertiseService;
	@Autowired
	PmsStatisticsService pmsStatisticsService;
	@Autowired
	PmsVisitLogService pmsVisitLogService;
	@Autowired
	PmsCommentService pmsCommentService;
	@Autowired
	private CmsMinutesService cmsMinutesService;
	@Autowired
	private CmsPageSetService cmsPageSetService;
	@Autowired
	private PmsNoticeService pmsNoticeService;
	@Autowired
	private PmsCrawlerService pmsCrawlerService;
	@Autowired
	private UmsUserService umsUserService;
	@Autowired
	private PmsImService pmsImService;
	@Autowired
	private UmsRoseService umsRoseService;
	@Autowired
	private PmsKeyWordService pmsKeyWordService;

	@Autowired
	private CustomersService customerService;

	@ApiOperation("获取主页配置")
	@GetMapping("/getPageInfo/{legalCode}")
	@ResponseBody
	public CommonResult<CorporationVO> getPageInfo(@PathVariable("legalCode") String legalCode,
			HttpServletRequest request) {
		if (StringUtils.isBlank(legalCode)) {
			log.info("法人编码为空");
			return CommonResult.failed("非法的URL地址");
		}

//		String url = request.getRequestURL().toString();

//        String url="http://192.168.1.9:8001/api";
//		int begin = url.indexOf("http://localhost:8001");
//		System.out.println("=============");
//		System.out.println(begin);
//		System.out.println("=============");
//		HashMap resultdata = cmsPageSetService.getPageInfo(begin);
		CorporationVO resultdata = cmsPageSetService.getPageInfo_new(legalCode);

		return CommonResult.success(resultdata);
	}

	// @ApiOperation("编辑主页配置")
	@RequestMapping(value = "/editPageInfo", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult editPageInfo(@RequestBody PmsPageSetItem pmsPageSetItem) {
		cmsPageSetService.editPageInfo(pmsPageSetItem);
		return CommonResult.success("保存成功");
	}

	// @ApiOperation("上传图片")
	@PostMapping("/fileupload")
	@ResponseBody
	public Object fileUpload(HttpServletRequest request, @RequestParam(value = "file") MultipartFile file) {
		String servletPath = request.getServletPath();
		String realPath = request.getSession().getServletContext().getRealPath(servletPath);
//      String servletPath = request.getServletPath();
		String url = request.getRequestURL().toString();
		String domain = url.replace(servletPath, "");
		RestResult restResult = new RestResult();
		try {
			request.setCharacterEncoding("utf-8");
			Object jsonObject = cmsMinutesService.uploadMinutes(request, file);

			restResult.setCode(200);
			restResult.setMessage("success");
			restResult.setData(jsonObject);

		} catch (Exception ex) {

		}
		return restResult;
	}

	/* 获取首页Banner图列表 */
	// @ApiOperation("获取滚动图列表")
	@RequestMapping(value = "/getAdvertises", method = RequestMethod.GET)
	@ResponseBody
	public CommonResult<List<SmsHomeAdvertise>> getAdvertises(HttpServletRequest request) {
		String url = request.getRequestURL().toString();
		System.out.println("=============");
		System.out.println(url);
		System.out.println("=============");
//        String url="http://192.168.1.9:8001/api";
		int begin = url.indexOf("http://localhost:8001");
		List<SmsHomeAdvertise> resultdata = smsHomeAdvertiseService.getAdvertises();
		if (begin != 0) {
			for (SmsHomeAdvertise advertise : resultdata) {
				String desurl = advertise.getUrl();
				String newurl = desurl.replaceAll("http://www.drxdh.cn:8001", "http://192.168.1.9:8001");
				advertise.setUrl(newurl);
			}
		}

		return CommonResult.success(resultdata);
	}

	/* banner图编辑 */
	// @ApiOperation("滚动图编辑")
	@RequestMapping(value = "/updateAdvertises", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult<SmsHomeAdvertise> updateAdvertises(@RequestBody SmsHomeAdvertise Advertise) {

		int resultdata = smsHomeAdvertiseService.saveOrUpdate_new(Advertise);
		if (resultdata > 0) {
			return CommonResult.success(Advertise);
		} else {
			return CommonResult.failed();
		}
	}

	// @ApiOperation("滚动图del")
	@RequestMapping(value = "/delAdvertises", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult delAdvertises(@RequestBody SmsHomeAdvertise Advertise) {
		String id = Advertise.getId();
		if (StringUtils.isEmpty(id)) {
			return CommonResult.failed("id不可为空");
		}
		int resultdata = smsHomeAdvertiseService.delete(id);
		if (resultdata > 0) {
			return CommonResult.success("删除成功");
		} else {
			return CommonResult.failed();
		}
	}
	/** 图片上传 暂缓处理 */

	/**/

	/**
	 * 记录栏目点击数量
	 */
	// @ApiOperation("记录栏目点击数量")
	// @RequestMapping(value = "/setColumnCount", method = RequestMethod.POST)
	// @ResponseBody
	public CommonResult setColumnCount(@RequestParam String columnCode) {
		int resultdata = pmsStatisticsService.saveOrUpdate(columnCode);
		if (resultdata > 0) {
			return CommonResult.success(resultdata);
		} else {
			return CommonResult.failed();
		}

	}

	@ApiOperation("记录栏目点击数量")
	@PostMapping(value = "/setColumnCount")
	@ResponseBody
	public CommonResult increaseColumnCount(@RequestBody @Validated({ VisitorClick.class }) VisitLogVO visitLogVO,
			HttpServletRequest request) {
//    	String ipAddress = IpUtils.getOutIP();
//    	if(StrUtil.isNotBlank(ipAddress)) {
//    		log.info("IP:{}的用户来访", IpUtils.getOutIP());
//    		visitLogVO.setOriginIp(ipAddress);
//    	}
		int resultdata = pmsVisitLogService.saveOrUpdate(visitLogVO);
		if (resultdata > 0) {
			return CommonResult.success();
		} else {
			return CommonResult.failed();
		}
	}

	/**
	 * 栏目点击数量
	 */
	// @ApiOperation("获取栏目点击数量")
	@RequestMapping(value = "/getColumnCount", method = RequestMethod.GET)
	@ResponseBody
	public CommonResult getColumnCount(@RequestParam String columnCode) {
		int resultdata = pmsStatisticsService.getPmsStatistics(columnCode);
		HashMap<String, Object> resultMap = new HashMap<>();
		if (resultdata > 0) {
			resultMap.put("count", resultdata);
			return CommonResult.success(resultMap);
		} else {
			return CommonResult.failed();
		}

	}

	/**
	 * 记录首页数量
	 */
	// @ApiOperation("记录首页访问数量")
	@RequestMapping(value = "/setVisitCount", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult setVisitCount() {
		String ip = getIp();

		int resultdata = pmsVisitLogService.setRecord(ip);
		HashMap<String, Object> resultMap = new HashMap<>();
		if (resultdata > 0) {
			resultMap.put("count", resultdata);
			return CommonResult.success(resultMap);
		} else {
			return CommonResult.failed();
		}

	}

	/**
	 * 获取首页数量
	 */
	// @ApiOperation("获取首页访问数量")
	@RequestMapping(value = "/getVisitCount", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult getVisitCount() {
		int resultCount = 0;
		resultCount = pmsVisitLogService.getVisitCount();

		HashMap<String, Object> resultMap = new HashMap<>();
		if (resultCount > 0) {
			resultMap.put("count", resultCount);
			return CommonResult.success(resultMap);
		} else {
			return CommonResult.failed();
		}

	}

	/**
	 * 获取留言数据列表
	 */
	// @ApiOperation("获取留言数据列表")
	@RequestMapping(value = "/getCommentList", method = RequestMethod.GET)
	@ResponseBody
	public CommonResult getCommentList() {
		List<PmsComment> result = pmsCommentService.findComentlist("");
		return CommonResult.success(result);
	}

	/**
	 * 留言保存
	 */
	// @ApiOperation("留言提交")
//	@RequestMapping(value = "/addComment", method = RequestMethod.POST)
//	@ResponseBody
	public CommonResult addComment(@RequestBody PmsComment pmsComment) {
		pmsComment.setId(UuidUtils.shortUuid());
		int result = pmsCommentService.insertPmsComment(pmsComment);
		if (result > 0) {
			HashMap<String, Object> resultMap = new HashMap<>();
			return CommonResult.success(resultMap);
		} else {
			return CommonResult.failed("提交失败");
		}
	}

	/**
	 * 提交留言
	 */
	@ApiOperation("留言提交")
	@PostMapping("/addComment")
	@ResponseBody
	public CommonResult submitComment(@RequestBody @Valid PmsCommentVO pmsCommentVO) {
		int result = pmsCommentService.submitComment(pmsCommentVO);
		if (result > 0) {
			HashMap<String, Object> resultMap = new HashMap<>();
			return CommonResult.success(resultMap);
		} else {
			return CommonResult.failed("提交失败");
		}
	}

	/**
	 * 留言审批
	 */
	// @ApiOperation("留言审批")
	@RequestMapping(value = "/addAudting", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult addAudting(@RequestBody PmsComment pmsComment) {
		int result = 0;
		String id = pmsComment.getId();
		result = pmsCommentService.audtingComment(id);

		if (result > 0) {
			HashMap<String, Object> resultMap = new HashMap<>();
			return CommonResult.success(resultMap);
		} else {
			return CommonResult.failed();
		}

	}

	/**
	 * 留言审批
	 */
	// @ApiOperation("留言记录")
	@RequestMapping(value = "/getAudting", method = RequestMethod.GET)
	@ResponseBody
	public CommonResult getAudting(@RequestBody PmsComment pmsComment) {
		String content = pmsComment.getContent();
		List<PmsComment> result = pmsCommentService.findComentlist(content);
		return CommonResult.success(result);
	}

	// @ApiOperation("留言删除")
	@RequestMapping(value = "/delComment", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult delComment(@RequestParam String id) {

		boolean result = pmsCommentService.removeById(id);
		if (result) {
			HashMap<String, Object> resultMap = new HashMap<>();
			return CommonResult.success();
		} else {
			return CommonResult.failed();
		}

	}

//	@ApiOperation("留言查询")
	@RequestMapping(value = "/queryComment", method = RequestMethod.GET)
	@ResponseBody
	public CommonResult delAudting(@RequestParam String content) {
		List<PmsComment> result = pmsCommentService.findComentlist(content);
		return CommonResult.success(result);

	}

	/**
	 * 公告提交
	 */
	// @ApiOperation("公告提交")
	@RequestMapping(value = "/addNotice", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult addNotice(@RequestBody PmsNotice pmsNotice) {
		int result = pmsNoticeService.saveNoticeData(pmsNotice);
		HashMap<String, Object> resultMap = new HashMap<>();
		return CommonResult.success(resultMap);
	}

	/**
	 * 公告提交
	 */
	// @ApiOperation("公告列表查询")
	@RequestMapping(value = "/getNoticeDatas", method = RequestMethod.GET)
	@ResponseBody
	public CommonResult<List<PmsNotice>> getNoticeDatas() {
		List<PmsNotice> resultList = pmsNoticeService.getNoticeDatas();
		return CommonResult.success(resultList);
	}

	/**
	 * 公告提交
	 */
	// @ApiOperation("公告列表查询")
	@RequestMapping(value = "/search", method = RequestMethod.GET)
	@ResponseBody
	public CommonResult<List<HashMap>> search(@RequestParam String keyname) {
//        pmsCrawlerService.getBaidu(keyname);
		List<HashMap> resultList = pmsCrawlerService.getBaidu(keyname);
//
		return CommonResult.success(resultList);
	}

	/**
	 * 记录栏目点击数量
	 */
//	 @ApiOperation("用户登陆")
//	@RequestMapping(value = "/login", method = RequestMethod.POST)
//	@ResponseBody
//	public CommonResult login(@RequestParam String username, @RequestParam String password) {
//		UmsUser umsUser = umsUserService.findUserByName(username);
//		if (password.equals(umsUser.getPassword())) {
//			return CommonResult.success(umsUser);
//		} else {
//			return CommonResult.failed("密码不正确");
//		}
//
//	}

	@ApiOperation("用户登陆")
	@PostMapping("/login")
	@ResponseBody
	public CommonResult login(@RequestBody @Validated LoginVO loginVO) {
		Customers user = customerService.getUserByUsername(loginVO.getUsername());
		if (Objects.isNull(user)) {
			return CommonResult.failed("用户不存在");
		}
		if (loginVO.getPassword().equals(user.getPassword())) {
			return CommonResult.success(user);
		} else {
			return CommonResult.failed("密码不正确");
		}

	}

	// @ApiOperation("用户注册")
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult register(@RequestBody UmsUser umsUser) {
		int result = umsUserService.saveorupdate(umsUser);
		if (result == 10000) {
			return CommonResult.failed("用户名已存在");
		}
		if (result > 0) {
			return CommonResult.success(umsUser);
		} else {
			return CommonResult.failed("保存失败");
		}

	}

	// @ApiOperation("用户注册")
	@RequestMapping(value = "/editUser", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult editUser(@RequestBody UmsUser umsUser) {
		int result = umsUserService.editUser(umsUser);

		if (result > 0) {
			return CommonResult.success(umsUser);
		} else {
			return CommonResult.failed("保存失败");
		}

	}

	// @ApiOperation("客服")
	@RequestMapping(value = "/getImdata", method = RequestMethod.GET)
	@ResponseBody
	public CommonResult getImdata(@RequestParam(name = "userid", defaultValue = "") String userid) {
		List<PmsIm> lists = pmsImService.getImDatas(userid);
		return CommonResult.success(lists);

	}

	// @ApiOperation("用户信息")
	@RequestMapping(value = "/getUsers", method = RequestMethod.GET)
	@ResponseBody
	public CommonResult getUser() {
		List<UmsUser> lists = umsUserService.getUser();
		return CommonResult.success(lists);

	}

	@ApiOperation("在线客服")
	@PostMapping("/getService")
	@ResponseBody
	public CommonResult<CustomersVO> getCustomerService(
			@RequestBody @Validated({ ClickService.class }) VisitLogVO visitLogVO) {
		CustomersVO customersVO = customerService.getCustomerServiceByCid(visitLogVO);
		return CommonResult.success(customersVO);
	}

	// @ApiOperation("用户删除")
	@RequestMapping(value = "/delUsers", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult delUser(@RequestBody UmsUser umsUser) {
		String id = umsUser.getId();
		if (id == null) {
			return CommonResult.failed("id不可为空");
		}
		int result = umsUserService.delete(umsUser);
		return CommonResult.success("success");

	}

	// @ApiOperation("关键字保存更新")
	@RequestMapping(value = "/updateKeyWord", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult updateKeyWord(@RequestBody PmsKeyWord keyWord) {
		Integer result = pmsKeyWordService.saveorupdate(keyWord);
		if (result > 0) {
			return CommonResult.success("保存成功");
		} else {
			return CommonResult.failed("保存失败");
		}

	}

	// @ApiOperation("获取 关键字内容")
	@RequestMapping(value = "/getKeyWord", method = RequestMethod.GET)
	@ResponseBody
	public CommonResult getKeyWord() {
		List<PmsKeyWord> resultList = pmsKeyWordService.getKeyWords();
		return CommonResult.success(resultList);
	}

	// @ApiOperation("删除关键字内容")
	@RequestMapping(value = "/delKeyWord", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult delKeyWord(@RequestParam Integer id) {
		Integer result = pmsKeyWordService.delete(id);
		if (result > 0) {
			return CommonResult.success(result);
		} else {
			return CommonResult.failed("删除失败");
		}
	}

	// @ApiOperation("获取角色信息")
	@RequestMapping(value = "/listRose", method = RequestMethod.GET)
	@ResponseBody
	public CommonResult listRose() {
		List<UmsRose> resultList = umsRoseService.getRose();
		return CommonResult.success(resultList);
	}

	// @ApiOperation("角色编辑")
	@RequestMapping(value = "/editRose", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult editRose(@RequestBody UmsRose umsRose) {
		Integer result = umsRoseService.saveorupdate(umsRose);
		if (result > 0) {
			return CommonResult.success("保存成功");
		} else {
			return CommonResult.failed("保存失败");
		}

	}

	// @ApiOperation("角色删除")
	@RequestMapping(value = "/delRose", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult delRose(@RequestParam Integer id) {
		Integer result = umsRoseService.delete(id);
		if (result > 0) {
			return CommonResult.success(result);
		} else {
			return CommonResult.failed("删除失败");
		}

	}

	// 获取请求对象
	private static HttpServletRequest getRequest() {
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		if (requestAttributes == null) {
			return null;
		} else {
			return requestAttributes.getRequest();
		}
	}

	// 获取请求的ip地址
	private static String getIp() {
		HttpServletRequest request = getRequest();
		if (request == null) {
			return "127.0.0.1";
		} else {
			return request.getRemoteHost();
		}
	}

}
